﻿using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class FollowTroopUI : MonoBehaviour {

    private Troop target;
    private Transform mTrans;
    public Camera gameCamera;
    public Camera uiCamera;
    private int index;
    private bool bIsHero = false;

    private bool b_work = false;

    private GameObject cub;

    public Vector3 offset=new Vector3(0,5,0);
    public int uiOffset = 0;

    // Update is called once per frame
    void Update () {
        Fresh();
	}

    public void Init(int TroopIndex,bool isHero,int heightOffSet)
    {
        BattleStage batStage = GameStageMachine.Instance.GetStage(GameStageType.Battle) as BattleStage;
        
        if (BattleMgr.Instance != null) {
            if (BattleMgr.Instance.TroopDic.ContainsKey(TroopIndex))
            {
                target = BattleMgr.Instance.TroopDic[TroopIndex];
                b_work = true;
                bIsHero = isHero;
                uiOffset = heightOffSet;
                gameCamera = batStage.GetCamera().GetComponent<Camera>();
                uiCamera = UICamera.currentCamera;
                mTrans = transform;
                this.index = TroopIndex;

                Fresh();
            }
        }
    }

    void OnDestroy()
    {
        if (cub != null)
        {
            Destroy(cub);
        }
    }

    private void Fresh() 
    {
        if (b_work)
        {
            if (!BattleStage.g_InBattle)
                return;

            if (target == null)
                return;

            if (cub == null)
            {
                cub = new GameObject();
                cub.name = index.ToString();
                cub.transform.SetParent(target.transform);
            }

            Vector3 pos = (bIsHero ? target.GetHeroHudPos() : target.GetTroopCenter()) + new Vector3(0, uiOffset, 0);
            //Vector3 pos = target.GetTroopCenter();
            pos = gameCamera.WorldToViewportPoint(pos);
            cub.transform.position = pos;
            transform.position = uiCamera.ViewportToWorldPoint(pos);
            pos = mTrans.localPosition;
            pos.x = Mathf.FloorToInt(pos.x);
            pos.y = Mathf.FloorToInt(pos.y);
            pos.z = 0f;
            mTrans.localPosition = pos;
        }
    }
}
